
import json
from encryption import Encryption
import logging

class SysConfigReader(object):

    sys_path="config/SysConfig.json"
    server = None
    service_config_path=""
    menu_data_path=""
    banner_path = ""    
    
    def print_banner(self):
        """打印banner"""
        with open(self.banner_path, 'r') as line:
            for l in line:
                print(l)
    
    def server_config_path(self):
        """获取serverConfig文件路径"""
        return self.service_config_path;
    
    def load_config(self,path):
        """根据文件路径加载配置"""
        try:
            with open(path,"r") as f:
                return json.load(f)
        except:
            logging.error("%s 加载配置文件失败，请检查配置内容是否为json格式",path)

    def load_sys_config(self):
        """加载sysConfig文件配置"""
        with open(self.sys_path,"r") as f:
            sys_config = json.load(f)    
            self.server = sys_config["server"]
            self.service_config_path = self.server["path"]
            self.banner_path = sys_config["banner_path"]
            self.menu_data_path = sys_config["menu_data_path"]

    def write_sys_file(self):
        """将 sysConfig 数据写入文件"""
        sys_dict = {"banner_path":self.banner_path,"menu_data_path":self.menu_data_path,"server":self.server}
        self.write_data_file(self.sys_path,sys_dict)

    def write_data_file(self,path,text):
        """将数据写入文件"""
        with open(path, 'w',encoding="utf-8") as file:
            json.dump(text, file)
    
    def server_list(self):
        """返回原始的服务器配置"""
        return self.load_config(self.service_config_path)
    
    def menu_data_config(self):
        """返回原始的服务器配置"""
        return self.load_config(self.menu_data_path)
    
    def server_encrypt_write(self):
        """服务器配置加密"""
        json_config = self.load_config(self.service_config_path)
        base64_encypt = Encryption.aes_encrypt(self.server["entryption_key"].encode(),str(json_config))
        encrpty_json={"d":base64_encypt}
        self.write_data_file(self.service_config_path,encrpty_json)

    def server_decrypt(self):
        """服务器配置解密"""
        encrypt_json = self.load_config(self.service_config_path)
        base64_encypt = encrypt_json["d"]
        decrpty_data = Encryption.aes_decrypt(self.server["entryption_key"].encode(),base64_encypt)
        # 字符串转json对象
        return json.loads(json.dumps(eval(decrpty_data)))
    
    def rest_server_config(self):
        """
        重置服务器配置到 config/ServerConfig.json
        """
        # 获取解析后的服务器配置
        server_config = self.server_decrypt()
        # 写入文件
        self.write_data_file(self.service_config_path,server_config)
        print("\033[32m   重置服务器配置成功...\033[0m")
        self.clear_encryption_key()
        print("\033[32m   清空加密key 成功...\033[0m \n")

    
    def clear_encryption_key(self):
        self.server["entryption_key"] = ""
        self.write_sys_file()
        